package com.homepig.mongodb;

import com.mongodb.MongoClient;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import com.mongodb.client.result.DeleteResult;
import org.bson.Document;

import static com.mongodb.client.model.Filters.eq;
import static java.util.Arrays.asList;

/**
 * 删除文档
 *
 * @author homepig
 * @version 1.0
 */
public class DeleteDocuments {
    private static MongoCollection mongoCollection;

    static {
        MongoClient mongoClient = new MongoClient("localhost", 27017);
        MongoDatabase mongoDatabase = mongoClient.getDatabase("mongo_stu");
        mongoCollection = mongoDatabase.getCollection("inventory");
        mongoCollection.drop();
        initData();
    }

    /**
     * 初始化数据
     */
    public static void initData() {
        mongoCollection.insertMany(asList(
                Document.parse("{ item: 'journal', qty: 25, size: { h: 14, w: 21, uom: 'cm' }, status: 'A' }"),
                Document.parse("{ item: 'notebook', qty: 50, size: { h: 8.5, w: 11, uom: 'in' }, status: 'A' }"),
                Document.parse("{ item: 'paper', qty: 100, size: { h: 8.5, w: 11, uom: 'in' }, status: 'D' }"),
                Document.parse("{ item: 'planner', qty: 75, size: { h: 22.85, w: 30, uom: 'cm' }, status: 'D' }"),
                Document.parse("{ item: 'postcard', qty: 45, size: { h: 10, w: 15.25, uom: 'cm' }, status: 'A' }")
        ));
    }


    /**
     * 删除集合下的所有文档
     */
    public void deleteAllDocuments() {
        DeleteResult deleteResult = mongoCollection.deleteMany(new Document());
        System.out.println(deleteResult.getDeletedCount());
    }

    /**
     * 删除集合下满足指定条件的所有文档
     */
    public void deleteAllDocumentsByCondition() {
        DeleteResult deleteResult = mongoCollection.deleteMany(eq("status", "D"));
        System.out.println(deleteResult.getDeletedCount());
    }

    /**
     * 删除单个文档
     */
    public void deleteOneDocument() {
        DeleteResult deleteResult = mongoCollection.deleteOne(eq("status", "D"));
        System.out.println(deleteResult.getDeletedCount());
    }

    public static void main(String[] args) {
        DeleteDocuments deleteDocuments = new DeleteDocuments();
        deleteDocuments.deleteAllDocuments();
        initData();
        deleteDocuments.deleteAllDocumentsByCondition();
        initData();
        deleteDocuments.deleteOneDocument();
    }
}
